﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPCaseDetailWUC.cs" company="Microsoft Corporation" author="David Martos" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Security.Application;


namespace CSP.WebParts.UserControls
{
    /// <summary>
    /// Shows the data of a Case, and allows the case update.
    /// </summary>    
    public class CSPCaseDetailWUC : CSPBaseWUC 
    {
       
        #region Members             
        protected Label lblTitle;
        protected Label lblActivityType;
        protected Label lblDocumentation;
        protected TextBox txbDueDate;
        protected Label lblContact;
        protected DropDownList ddlStatusItems;
        protected Button CaseDetailUpdate;
        protected Panel pnlCaseDetail;
        protected Panel pnlCaseDetailResult;
        const string ID = "id";
        #endregion


        #region PageEvents
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {               
                if (!Page.IsPostBack)
                {
                    this.LoadLabels();
                    this.LoadData();
                }               
            }         
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                this.CaseDetailUpdate.Click += new EventHandler(CaseDetailUpdate_Click);
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailCreateChildControlsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion


        #region Methods
        /// <summary>
        /// Sets the value of the labels using the resource file with localized values.
        /// </summary>         
        protected void LoadLabels()
        {
            try
            {
                base.LoadLabels(this.pnlCaseDetail);
                base.LoadLabels(this.pnlCaseDetailResult);
            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadLabelsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }

        }

        /// <summary>
        /// Validates the input of this webpart format matches the guid one
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected bool ValidateInput(string input)
        {
            try
            {
                System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter();
                guidConverter.ConvertFromString(input);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Gets and validates the case id to be found in the querystring
        /// </summary>
        /// <returns></returns>
        protected string GetCaseID()
        {
            string caseID = string.Empty;

            if (Context.Request.QueryString[ID] != null)
                caseID = Context.Request.QueryString[ID];

            if (String.IsNullOrEmpty(caseID))
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name);
                WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPGenericErrorMessage));
                throw new CSP.Core.CSPException(WebPartConstants.CSPCaseDetailNoIDErrorMessage);
            }

            if (ValidateInput(caseID))
            {
                return caseID;
            }
            else
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name);
                WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPGenericErrorMessage));
                throw new CSP.Core.CSPException(WebPartConstants.CSPCaseDetailNoIDErrorMessage);
            }
        }
        /// <summary>
        /// Gets the data of and specified Case.
        /// </summary>          
        private void LoadData()
        {
            CSP.MembershipInterface.MembershipServiceClient client = null;

            try
            {
                string caseID = GetCaseID();

                client = new CSP.MembershipInterface.MembershipServiceClient();

                CSP.MembershipInterface.ObjectModel.Case crmCase = client.GetCaseByCaseID(caseID);
                if (crmCase != null)
                {
                    this.lblTitle.Text = AntiXss.HtmlEncode(crmCase.Title);
                    this.lblActivityType.Text = AntiXss.HtmlEncode(crmCase.Type.CaseTypeTitle.ToString());

                    this.lblDocumentation.Text = "";

                    if (crmCase.DueDate != null)
                        this.txbDueDate.Text = crmCase.DueDate.ToShortDateString();

                    CSP.MembershipInterface.ObjectModel.CaseStatus[] cs = client.GetCaseStatus();

                    foreach (CSP.MembershipInterface.ObjectModel.CaseStatus status in cs)
                    {
                        this.ddlStatusItems.Items.Add(new ListItem(status.CaseStatusTitle.ToString(), status.CaseStatusId.ToString()));
                    }
                    this.ddlStatusItems.SelectedValue = crmCase.Status.CaseStatusId.ToString();

                    this.lblContact.Text = string.Empty;
                    StringBuilder contact = new StringBuilder();
                    if (crmCase.RequestorName != null)
                        contact.AppendLine(AntiXss.HtmlEncode(crmCase.RequestorName) + "<br/>");
                    if (crmCase.RequestorEmail != null)
                        contact.AppendLine(AntiXss.HtmlEncode(crmCase.RequestorEmail) + "<br/>");
                    if (crmCase.RequestorPhone != null)
                        contact.AppendLine(AntiXss.HtmlEncode(crmCase.RequestorPhone));
                    this.lblContact.Text = contact.ToString();
                }
                else
                {
                    WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPGenericErrorMessage));
                    throw new CSP.Core.CSPException(WebPartConstants.CSPCaseDetailNullErrorMessage);
                }

            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name, ex);
                WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPGenericErrorMessage));
                throw new CSP.Core.CSPException(ex);
            }           
        }


        /// <summary>
        /// Updates the data of and specified Case.
        /// </summary>       
        private void Update()
        {
            CSP.MembershipInterface.MembershipServiceClient client = null;
            try
            {
                string caseID = GetCaseID();

                client = new CSP.MembershipInterface.MembershipServiceClient();

                CSP.MembershipInterface.ObjectModel.Case crmCase = client.GetCaseByCaseID(caseID);
                if (crmCase != null)
                {
                   CSP.MembershipInterface.ObjectModel.CaseStatus oldCaseStatus = crmCase.Status;

                    
                   crmCase.Status = client.GetCaseStatusByCaseStatusID (Convert.ToInt32 (this.ddlStatusItems.SelectedValue));

                    if (this.txbDueDate.Text.Length > 0)
                    {
                        try
                        {
                            crmCase.DueDate = DateTime.Parse(this.txbDueDate.Text);
                        }
                        catch (Exception ex) 
                        {
                            this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name, ex);
                        }
                    }

                    client.UpdateCase(crmCase);

                    client.Close();

                    this.pnlCaseDetail.Visible = false;
                    this.pnlCaseDetailResult.Visible = true; 
                }
                else
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name);
                    throw new CSP.Core.CSPException(WebPartConstants.CSPCaseDetailNullErrorMessage);
                }
            }       
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
            finally
            {
                if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                    client.Close();
            }
        }
        #endregion
            

        #region ControlEvents
        void CaseDetailUpdate_Click(Object sender, EventArgs e) {
            try
            {
                this.Update();
                this.LoadData();
            }         
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCaseDetailUpdateErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion
    }
}
